package com.example.elasticsearchhepler.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.elasticsearchhepler.annotations.ESDocument;
import com.example.elasticsearchhepler.service.ElasticsearchIndexService;
import com.example.elasticsearchhepler.utils.ElasticSearchHelpUtils;
import com.example.elasticsearchhepler.utils.EmptyUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 索引数据库的创建、删除、存在
 **/
@Service
@Slf4j
public class ElasticsearchIndexServiceImpl<T> implements ElasticsearchIndexService<T> {

    @Resource
    private RestHighLevelClient client;

    @Resource
    private ElasticSearchHelpUtils<T> elasticSearchHelpUtils;

    /**
     * 判断索引是否存在
     * @param clazz
     * @return
     * @throws Exception
     */
    @Override
    public boolean exists(Class<T> clazz) throws Exception{
        GetIndexRequest request = new GetIndexRequest(elasticSearchHelpUtils.getIndexName(clazz));
        return client.indices().exists(request, RequestOptions.DEFAULT);
    }

    @Override
    public Boolean createIndex(Class<T> clazz) throws Exception{
        ESDocument document = clazz.getAnnotation(ESDocument.class);
        String indexName = elasticSearchHelpUtils.getOnlyIndexName(clazz);

        if(Boolean.FALSE.equals(document.createIndex())){
            return false;
        }
        CreateIndexRequest request = new CreateIndexRequest(indexName);

        //设置setting
        request.settings(Settings.builder()
                .put("index.number_of_shards", document.shards())
                .put("index.number_of_replicas", document.replicas())
                .put("index.refresh_interval", document.refreshInterval()));//设置settings

        //设置索引别名
        if (EmptyUtil.isNotEmpty(document.indexAliasesName())){
            Alias alias = new Alias(document.indexAliasesName());
            alias.writeIndex(true);
            request.alias(alias);
        }

        //设置mapping
        request.mapping(JSON.toJSONString(elasticSearchHelpUtils.getMapping(clazz)),XContentType.JSON);

        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        boolean acknowledged = createIndexResponse.isAcknowledged();
        log.info("============索引库indexName：{}创建结果acknowledged：{}", indexName, acknowledged);
        return acknowledged;
    }

    @Override
    public boolean dropIndex(Class<T> clazz) throws Exception {
        DeleteIndexRequest request = new DeleteIndexRequest(elasticSearchHelpUtils.getIndexName(clazz));
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        return response.isAcknowledged();
    }

}
